import React, { useState, useEffect } from 'react';
import {
  Table,
  Card,
  Button,
  Space,
  Tag,
  Modal,
  Form,
  Input,
  Select,
  Switch,
  message,
  Popconfirm,
  Typography,
  Row,
  Col,
  Statistic
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  ReloadOutlined,
  ToolOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons';

import { toolService } from '../services/tool';
import { Tool } from '../types';

const { Title } = Typography;
const { Option } = Select;

const ToolManagement: React.FC = () => {
  const [tools, setTools] = useState<Tool[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingTool, setEditingTool] = useState<Tool | null>(null);
  const [form] = Form.useForm();

  // 统计数据
  const [stats, setStats] = useState({
    total: 0,
    active: 0,
    inactive: 0
  });

  useEffect(() => {
    loadTools();
  }, []);

  const loadTools = async () => {
    try {
      setLoading(true);
      const response = await toolService.getAllTools();
      const toolData = response.data || [];
      setTools(toolData);
      
      // 计算统计数据
      const total = toolData.length;
      const active = toolData.filter((tool: Tool) => tool.status === 'active').length;
      const inactive = total - active;
      setStats({ total, active, inactive });
    } catch (error) {
      message.error('加载工具列表失败');
      console.error('加载工具失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleCreate = () => {
    setEditingTool(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (tool: Tool) => {
    setEditingTool(tool);
    form.setFieldsValue(tool);
    setModalVisible(true);
  };

  const handleDelete = async (toolId: number) => {
    try {
      await toolService.deleteTool(toolId);
      message.success('删除成功');
      loadTools();
    } catch (error) {
      message.error('删除失败');
      console.error('删除工具失败:', error);
    }
  };

  const handleSubmit = async (values: any) => {
    try {
      if (editingTool) {
        await toolService.updateTool(editingTool.id, values);
        message.success('更新成功');
      } else {
        await toolService.createTool(values);
        message.success('创建成功');
      }
      setModalVisible(false);
      loadTools();
    } catch (error) {
      message.error(editingTool ? '更新失败' : '创建失败');
      console.error('提交工具失败:', error);
    }
  };

  const getStatusColor = (status: string) => {
    return status === 'active' ? 'success' : 'default';
  };

  const getStatusIcon = (status: string) => {
    return status === 'active' ? <CheckCircleOutlined /> : <ExclamationCircleOutlined />;
  };

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 100,
    },
    {
      title: '工具名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record: Tool) => (
        <Space>
          <ToolOutlined />
          <strong>{text}</strong>
        </Space>
      ),
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: '类别',
      dataIndex: 'category',
      key: 'category',
      render: (category: string) => (
        <Tag color="blue">{category}</Tag>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Tag
          color={getStatusColor(status)}
          icon={getStatusIcon(status)}
        >
          {status === 'active' ? '活跃' : status === 'inactive' ? '非活跃' : '维护中'}
        </Tag>
      ),
    },
    {
      title: 'URL',
      dataIndex: 'url',
      key: 'url',
      ellipsis: true,
      render: (url: string) => url ? (
        <a href={url} target="_blank" rel="noopener noreferrer">
          {url}
        </a>
      ) : '-',
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      render: (_: any, record: Tool) => (
        <Space>
          <Button
            type="primary"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个工具吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              danger
              size="small"
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <div style={{ marginBottom: 24 }}>
        <Title level={2}>
          <ToolOutlined /> 工具管理
        </Title>
      </div>

      {/* 统计卡片 */}
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={8}>
          <Card>
            <Statistic
              title="总工具数"
              value={stats.total}
              prefix={<ToolOutlined />}
            />
          </Card>
        </Col>
        <Col span={8}>
          <Card>
            <Statistic
              title="活跃工具"
              value={stats.active}
              valueStyle={{ color: '#3f8600' }}
              prefix={<CheckCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={8}>
          <Card>
            <Statistic
              title="非活跃工具"
              value={stats.inactive}
              valueStyle={{ color: '#cf1322' }}
              prefix={<ExclamationCircleOutlined />}
            />
          </Card>
        </Col>
      </Row>

      {/* 工具列表卡片 */}
      <Card
        title="工具列表"
        extra={
          <Space>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={handleCreate}
            >
              新建工具
            </Button>
            <Button
              icon={<ReloadOutlined />}
              onClick={loadTools}
              loading={loading}
            >
              刷新
            </Button>
          </Space>
        }
      >
        <Table
          columns={columns}
          dataSource={tools}
          rowKey="id"
          loading={loading}
          pagination={{
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
          }}
        />
      </Card>

      {/* 新建/编辑工具模态框 */}
      <Modal
        title={editingTool ? '编辑工具' : '新建工具'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        onOk={() => form.submit()}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Form.Item
            name="name"
            label="工具名称"
            rules={[
              { required: true, message: '请输入工具名称' },
              { max: 50, message: '名称不能超过50个字符' }
            ]}
          >
            <Input placeholder="请输入工具名称" />
          </Form.Item>

          <Form.Item
            name="description"
            label="工具描述"
            rules={[
              { required: true, message: '请输入工具描述' },
              { max: 200, message: '描述不能超过200个字符' }
            ]}
          >
            <Input.TextArea
              placeholder="请输入工具描述"
              rows={3}
            />
          </Form.Item>

          <Form.Item
            name="category"
            label="工具类别"
            rules={[{ required: true, message: '请选择工具类别' }]}
          >
            <Select placeholder="请选择工具类别">
              <Option value="web">Web应用</Option>
              <Option value="api">API服务</Option>
              <Option value="tool">命令行工具</Option>
              <Option value="service">后台服务</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="version"
            label="版本"
            rules={[{ required: true, message: '请输入版本号' }]}
          >
            <Input placeholder="1.0.0" />
          </Form.Item>

          <Form.Item
            name="url"
            label="访问URL"
            rules={[
              { type: 'url', message: '请输入有效的URL' }
            ]}
          >
            <Input placeholder="http://example.com" />
          </Form.Item>

          <Form.Item
            name="status"
            label="状态"
            initialValue="active"
          >
            <Select>
              <Option value="active">活跃</Option>
              <Option value="inactive">非活跃</Option>
              <Option value="maintenance">维护中</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default ToolManagement;
